<template>
    <view class="form-container bg" :scroll-y="true">
        <u-sticky offset-top="10">
            <u-button @click="onScanBtn" size="normal" :icon="ruleForm.auditState !== 1 ? 'scan' : ''">
                <text v-if="ruleForm.auditState !== 1">点击扫码，当前品种: {{ ruleForm.itemList ? ruleForm.itemList.length : 0 }}个</text>
                <text v-else>出库品种: {{ ruleForm.itemList ? ruleForm.itemList.length : 0 }}个</text>
            </u-button>
        </u-sticky>
        <view class="margin-top-20">
            <jkFormCard title="基础信息" :show-right-icon="true">
                <u-icon v-if="!ruleForm.auditState" slot="right" name="trash" size="24" @click="onDeleteBtn"></u-icon>
                <jk-form-item label="出库单号" :show-right-icon="false">
                    <view class="flex-between-center width-100-percentage">
                        <view>{{ ruleForm.code || '系统自动生成' }}</view>
                        <u-tag v-if="ruleForm.id" :text="ruleForm.auditState ? '已审核' : '待审核'" plain size="mini" :type="ruleForm.auditState ? 'success' : 'error'"></u-tag>
                    </view>
                </jk-form-item>
                <jk-form-item label="客户" :show-right-icon="ruleForm.auditState !== 1" @click="toSearchCustomer" :show-star="ruleForm.auditState !== 1" :value="ruleForm.customerId" @clear="onConfirmOfSelectCustomer(null,{})">
                    <view>{{ ruleForm.customerName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="结算客户" :show-star="false" :show-right-icon="false">
                    <view>{{ ruleForm.settleCustomerName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="输出仓库" :show-right-icon="ruleForm.auditState !== 1" :show-star="ruleForm.auditState !== 1" @click="onSelectWarehouse('father')" :value="ruleForm.warehouseName" @clear="onClearFatherWarehouse">
                    <view>{{ ruleForm.warehouseName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="出库时间" :show-right-icon="ruleForm.auditState !== 1" @click="onSelectTime('belongDateTime')" :value="ruleForm.belongDateTime" @clear="ruleForm.belongDateTime = ''">
                    <view>{{ ruleForm.belongDateTime || '' }}</view>
                </jk-form-item>
                <jk-form-item label="备注" label-position="top" :show-border-bottom="false">
                   <textarea
                       placeholder-class="color4"
                       class="textarea-style"
                       :cursor-spacing="100"
                       style="height: 80rpx;"
                       :disabled="ruleForm.auditState === 1"
                       :adjust-position="true"
                       v-model="ruleForm.remark"
                       placeholder="请输入"
                   ></textarea>
                </jk-form-item>
            </jkFormCard>
        </view>
        <view
            v-for="(productItem, productIndex) in ruleForm.itemList"
            :key="productIndex"
            class="margin-top-30">
            <jkFormCard :show-right-icon="true">
                <view slot="header">{{ productItem.productName || '暂无' }}</view>
                <u-icon v-if="!ruleForm.auditState" slot="right" name="trash" color="red" size="24" @click="ruleForm.itemList.splice(productIndex, 1)"></u-icon>
                <jk-form-item label="批号" :show-right-icon="false">
                    <view>{{ productItem.batchCode || '' }}</view>
                </jk-form-item>
                <jk-form-item label="分类" :show-right-icon="false">
                    <view>{{ productItem.categoryName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="出库仓库" :show-right-icon="ruleForm.auditState !== 1" @click="onSelectWarehouse('child', productIndex)" :show-star="ruleForm.auditState !== 1" :value="productItem.warehouseName" @clear="onClearWarehouse(productIndex)">
                    <view>{{ productItem.warehouseName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="出库数量" :show-right-icon="ruleForm.auditState !== 1" :show-star="ruleForm.auditState !== 1" :value="productItem.outInNumber" @clear="productItem.outInNumber = ''" right-icon="edit-pen">
                    <view v-if="ruleForm.auditState !== 1">
                        <u-input v-model="productItem.outInNumber" @blur="onTransferNumber($event, 'outInNumber', productIndex)" :customStyle="{paddingLeft: 0}" :holdKeyboard="false" :adjustPosition="true" :cursorSpacing="30" type="digit" fontSize="28rpx" inputAlign="left" placeholder="出库数量" border="surround"></u-input>
                    </view>
                    <text v-else>{{ productItem.outInNumber || '0' }}</text>
                </jk-form-item>
                <jk-form-item label="出前库存" :show-right-icon="false" :show-border-bottom="false">
                    <view>{{ productItem.beforeNumber || '0' }}</view>
                </jk-form-item>
            </jkFormCard>
        </view>
        <view class="flex-center margin-top-20" v-if="!ruleForm.auditState">
            <u-button icon="plus-circle" :disabled="!ruleForm.customerId" @click="onAddProductBtn">添加</u-button>
        </view>
		<view class="fixed-footer">
            <view style="width: 100%;padding-right: 10rpx;"><u-button style="width: 100%;" @click="onConfirmBtn(0)" :disabled="ruleForm.auditState === 1" :loading="saveLoading" size="large" type="primary">保存</u-button></view>
            <view style="width: 100%;padding-left: 10rpx;"><u-button style="width: 100%;" @click="onConfirmBtn(1)" :disabled="ruleForm.auditState === 1" :loading="confirmLoading" size="large" type="success">保存并出库</u-button></view>
		</view>
		<u-datetime-picker
            v-model="selectDateTime"
            :show="selectDateTimePickerState"
            mode="datetime"
			:closeOnClickOverlay="true"
            @confirm="onConfirmBtnOfSelectPicker"
            @close="onCloseBtnOfSelectPicker"
			@cancel="onCloseBtnOfSelectPicker"
        ></u-datetime-picker>
        <jkPopupOption
            :showAll="false"
            :value="selectProductItemWarehouseId"
            :show="selectWarehousePopupOptionState"
            :optionList="warehouseList"
            @visible-change="(e) => selectWarehousePopupOptionState = e"
            @confirm="onConfirmOfSelectWarehouse"
        ></jkPopupOption>
        <jkPopupOption
            :value="ruleForm.customerId"
            :show="selectCustomerPopupOptionState"
            :optionList="customerList"
            @visible-change="(e) => selectCustomerPopupOptionState = e"
            @confirm="onConfirmOfSelectCustomer"
        ></jkPopupOption>
	</view>
</template>

<script>
import {
    productionPackagePlanGet,
    productionStockOutRecordCreate, productionStockOutRecordDelete,
    productionStockOutRecordGet,
    productionStockOutRecordUpdate, productionStockOutRecordUpdateAuditState,
    spinCustomerPage,
    yongYouInventoryProductStockTotal,
    yongYouWarehouseList
} from "../../../../api";
import {
    formatDate,
    formatTime,
    showLoading, tipBar
} from "../../../../utils/jk-utils";
        import jkPopup from '../../../../jk-components/jk-popup';
    import jkFormCard from "../../../../jk-components/jk-from-card";
    import jkFormItem from "../../../../jk-components/jk-from-item";
    import jkPopupOption from "../../../../jk-components/jk-popup-option";
import getNoticeBatchInfo from "../packagePlan/getNoticeBatchInfo";
	export default {
        mixins: [getNoticeBatchInfo],
        components: {
            jkPopupOption,
            jkFormCard,
            jkFormItem,
			jkPopup
		},
		data() {
			return {
                selectWarehouseFrom: 'father',
                customerList: [],
                selectCustomerPopupOptionState: false,
                selectProductItemWarehouseId: null,
                selectWarehousePopupOptionState: false,
                warehouseList: [],
				selectDateTime: '',
				selectDateTimePickerState: false,
				confirmLoading: false,
                saveLoading: false,
				dataId: null,
                selectProductItemIndex: null,
                defaultProductItem: {
                    "batchCode": "",
                    "batchId": 0,
                    "beforeNumber": 0,
                    "bundleList": [],
                    "empCode": "",
                    "empId": 0,
                    "empName": "",
                    "innerBagList": [],
                    "invalidDateTime": "",
                    "number": 0,
                    "outerBagList": [],
                    "packingPlanCode": "",
                    "packingPlanId": 0,
                    "paperTubeList": [],
                    "productCode": "",
                    "productId": 0,
                    "productName": "",
                    "productionDateTime": "",
                    "remark": "",
                    "suttle": 0,
                    "type": 0,
                    "warehouseCode": "",
                    "warehouseId": 0,
                    "warehouseName": "",
                    "workshopCode": "",
                    "workshopId": 0,
                    "workshopName": ""
                },
				ruleForm: {
                    auditState: 0,
                    itemList: [],
                    customerId: '',
                    customerCode: '',
                    customerName: '',
                    belongDateTime: '',
                    settleCustomerName: '',
                    remark: ''
                },
			}
		},
		onLoad(e) {
            this.dataId = e.id;
            this.getDependentData();
        },
		onShow() {
		},
		methods: {
            onAddProductBtn() {
                uni.navigateTo({
                    url: '/pages/production/packagePrd/outWarehouse/searchNotice'
                });
            },
		    // 获取搜素页的数据
            getCustomerData(item) {
                this.$set(this.ruleForm, 'customerId', item.id);
                this.$set(this.ruleForm, 'customerCode', item.code);
                this.$set(this.ruleForm, 'customerName', item.name);

                this.$set(this.ruleForm, 'settleCustomerId', item.settleCustomerId);
                this.$set(this.ruleForm, 'settleCustomerCode', item.settleCustomerCode);
                this.$set(this.ruleForm, 'settleCustomerName', item.settleCustomerName);
            },
		    toSearchCustomer() {
                if (this.ruleForm.auditState !== 1) {
                    wx.navigateTo({
                        url: '/pages/production/packagePrd/outWarehouse/searchCustomer'
                    });
                }
            },
            onDeleteBtn() {
                let _this = this;
                uni.showModal({
                    title: '提示',
                    content: `确定删除出库单吗？`,
                    success(res) {
                        if (res.confirm) {
                            productionStockOutRecordDelete({id: _this.dataId}).then(res => {
                                if (res.data.status === 200) {
                                    uni.navigateBack({
                                        delta: 1
                                    });
                                }
                            });
                        }
                    }
                });
            },
            onConfirmOfSelectCustomer(e, item) {
                this.$set(this.ruleForm, 'customerId', item.id);
                this.$set(this.ruleForm, 'customerCode', item.code);
                this.$set(this.ruleForm, 'customerName', item.name);

                this.$set(this.ruleForm, 'settleCustomerId', item.id);
                this.$set(this.ruleForm, 'settleCustomerCode', item.code);
                this.$set(this.ruleForm, 'settleCustomerName', item.name);
                this.selectCustomerPopupOptionState = false;
            },
            onBlurPlanCode(e, index) {
                this.selectProductItemIndex = index;
                this.getDataDetailRequest(e);
            },
            onSelectWarehouse(from, index) {
                if (this.ruleForm.auditState !== 1) {
                    this.selectWarehouseFrom = from;
                    if (from === 'father') {
                        this.selectProductItemWarehouseId = this.ruleForm.warehouseId;
                    } else {
                        this.selectProductItemIndex = index;
                        this.selectProductItemWarehouseId = this.ruleForm.itemList[index].warehouseId;
                    }
                    this.selectWarehousePopupOptionState = true;
                }
            },
            onClearWarehouse(index) {
                this.$set(this.ruleForm.itemList[index], 'beforeNumber', 0);
                this.$set(this.ruleForm.itemList[index], 'outInNumber', 0);
                this.$set(this.ruleForm.itemList[index], 'warehouseId', '');
                this.$set(this.ruleForm.itemList[index], 'warehouseCode', '');
                this.$set(this.ruleForm.itemList[index], 'warehouseName', '');
            },
            onClearFatherWarehouse() {
                this.selectWarehouseFrom = 'father';
                this.onConfirmOfSelectWarehouse(null, {});
            },
            onConfirmOfSelectWarehouse(e, item) {
                if (this.selectWarehouseFrom === 'father') {
                    this.$set(this.ruleForm, 'warehouseId', item.id);
                    this.$set(this.ruleForm, 'warehouseCode', item.code);
                    this.$set(this.ruleForm, 'warehouseName', item.name);
                } else {
                    this.$set(this.ruleForm.itemList[this.selectProductItemIndex], 'warehouseId', item.id);
                    this.$set(this.ruleForm.itemList[this.selectProductItemIndex], 'warehouseCode', item.code);
                    this.$set(this.ruleForm.itemList[this.selectProductItemIndex], 'warehouseName', item.name);
                    // 更新库存
                    this.getProductItemStockRequest(this.ruleForm.itemList[this.selectProductItemIndex]).then(res => {
                        if (res.data.status === 200) {
                            let val = res.data.res.availableQuantity || 0;
                            val = Number(val);
                            this.$set(this.ruleForm.itemList[this.selectProductItemIndex], 'outInNumber', val);
                            this.$set(this.ruleForm.itemList[this.selectProductItemIndex], 'beforeNumber', val);
                        }
                    });
                }
                this.selectWarehousePopupOptionState = false;

            },
            onSelectTime(type) {
                if (this.ruleForm.auditState !== 1) {
                    this.timeType = type;
                    this.selectDateTimePickerState = true;
                }
            },
            onScanBtn() {
                if (this.ruleForm.auditState === 1) return;
                let _this = this;
                // 允许从相机和相册扫码
                uni.scanCode({
                    success: function (res) {
                        let scanData = '';
                        try {
                            scanData = res.result;
                        } catch {
                            wx.showToast({
                                title: '无效的二维码',
                                icon: 'error'
                            })
                        }
                        if (scanData) {
                            wx.showModal({
                                title: '扫码结果',
                                content: `通知单:${scanData}`,
                                success(res) {
                                    if (res.confirm) {
                                        _this.getDataDetailRequest(scanData);
                                    }
                                }
                            })
                        } else {
                            wx.showToast({
                                title: '二维码格式不符',
                                icon: 'error'
                            })
                        }
                    }
                });

            },
            getDataDetailRequest(scanData) {
                this.getNoticeDetailRequest(scanData).then(res => {
                    if (res.data.status === 200) {
                        let resData = this.transferData(res.data.res || {});
                        resData.warehouseId = this.ruleForm.warehouseId;
                        resData.warehouseCode = this.ruleForm.warehouseCode;
                        resData.warehouseName = this.ruleForm.warehouseName;
                        resData.beforeNumber = 0;
                        resData.productionDateTime = formatTime(Date.now());
                        resData.invalidDateTime = '';
                        delete resData.id;
                        this.getProductItemStockRequest(resData).then(res => {
                            if (res.data.status === 200) {
                                let val = res.data.res.availableQuantity || 0;
                                val = Number(val);
                                resData.outInNumber = val;
                                resData.beforeNumber = val;
                                this.ruleForm.itemList.push(resData);
                            }
                        });
                    }
                });
            },
            getDetailRequest() {
                return productionStockOutRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        let resData = res.data.res || {};
                        resData.itemList = resData.itemList ? resData.itemList : [];
                        this.ruleForm = resData;
                    }
                });
            },
            onTransferNumber(e, type, index) {
                this.$set(this.ruleForm.itemList[index], type, Number(e));
            },
			onCloseBtnOfSelectPicker() {
				this.selectDateTimePickerState = false;
			},
			onConfirmBtnOfSelectPicker(e) {
				this.$set(this.ruleForm, this.timeType, formatTime(e.value));
				this.selectDateTimePickerState = false;
			},
			onConfirmBtn(e) {
                let params = JSON.parse(JSON.stringify(this.ruleForm));
                params.belongDate = params.belongDateTime ? formatDate(params.belongDateTime) : '';
                params.auditState = e;
                let hasNull = this.ruleForm.itemList.some(x => !x.warehouseId || !x.outInNumber || !x.packingPlanCode);
                let api = this.dataId ? productionStockOutRecordUpdate : productionStockOutRecordCreate;
                if (!hasNull && params.customerId && params.warehouseId && this.ruleForm.itemList && this.ruleForm.itemList.length) {
                    if (!e) {
                        this.saveLoading = true;
                    } else {
                        this.confirmLoading = true;
                    }
                    api(params).then(res => {
                        if (!e) {
                            this.saveLoading = false;
                        } else {
                            this.confirmLoading = false;
                        }
                        if (res.data.status === 200) {
                            uni.navigateBack({
                                delta: 1
                            });
                            tipBar('save');
                        }
                    })
                } else {
                    uni.showToast({
                        title: '请填写完成',
                        icon: 'error'
                    });
                }
			},
            getWarehouseListRequest() {
                return yongYouWarehouseList().then(res => {
                    if (res.data.status === 200) {
                        this.warehouseList = res.data.res;
                    }
                });
            },
            getCustomerListRequest() {
                return spinCustomerPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.customerList = res.data.res;
                    }
                });
            },
            getProductItemStockRequest(resData) {
                if (resData.warehouseCode && resData.productId && resData.batchCode) {
                    return yongYouInventoryProductStockTotal({
                        warehouseCode:  resData.warehouseCode,
                        productId:  resData.productId,
                        batchCode:  resData.batchCode,
                    });
                } else {
                    return new Promise((resolve) => resolve({
                        data: {
                            status: 200,
                            res: {
                                availableQuantity: 0
                            }
                        }
                    }))
                }
            },
			async getDependentData() {
                this.$set(this.ruleForm, 'belongDateTime', formatTime(Date.now()));
                showLoading(true);
				this.selectDateTime = formatTime(Date.now());
                await this.getWarehouseListRequest();
                await this.getCustomerListRequest();
				if (this.dataId) await this.getDetailRequest();
				showLoading(false);
			}
		}
	}
</script>

<style>

</style>
<style lang="scss" scoped>
	.machine-title {
		height: 42px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2d8cf0;
		border-radius: 12rpx;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
        border: solid 1px #2d8cf0;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		margin: 10rpx;
	}
	.popup-content-box {
		padding: 32rpx;
		.popup-content-box-title {
			font-size: 34rpx;
			text-align: center;
			margin-bottom: 20rpx;
		}
	}
</style>
